#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>

#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */
#include <fcntl.h>           /* For O_* constants */

#include "shm_com.h"

int main(void)
{
    int running = 1;
    void* shared_memory = NULL;
    struct shared_use_st* shared_stuff;

    srand((unsigned int)getpid());
    int fd = shm_open(SHM_FILE_NAME, O_CREAT | O_RDWR | O_TRUNC, 0666);
    if (-1 == fd)
    {
        perror("shm_open failed\n");
        exit(EXIT_FAILURE);
    }
    ftruncate(fd, SHM_BUF_SIZE);

    shared_memory = mmap(NULL, SHM_BUF_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (MAP_FAILED == shared_memory)
    {
        perror("mmap failed\n");
        exit(EXIT_FAILURE);
    }
    printf("memory attached at %p\n", shared_memory);

    shared_stuff = (struct shared_use_st*)shared_memory;
    shared_stuff->written_by_you = 0;
    while(running)
    {
        if (shared_stuff->written_by_you)
        {
            printf("You wrote: %s", shared_stuff->some_text);
            sleep(rand() % 4);
            shared_stuff->written_by_you = 0;
            if (strncmp(shared_stuff->some_text, "end", 3) == 0)
            {
                running = 0;
            }
        }
    }

    if (-1 == munmap(shared_memory, SHM_BUF_SIZE))
    {
        perror("munmap failed\n");
        exit(EXIT_FAILURE);
    }

    if (-1 == shm_unlink(SHM_FILE_NAME))
    {
        perror("shm_unlink failed\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}
